//
//  LZHomePageViewController.m
//  laziz_Consumer
//
//  Created by XMac on 16/10/24.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZHomePageViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UIButton+TransitionEdgeInsets.h"
#import "LZVideoCellPresenter.h"
#import "LZSearchCollectionView.h"
#import "LZVideoTableViewCell.h"
#import "LZRestaurantFiltersView.h"
#import "LZCustomPlayerView.h"
#import "LZMapViewController.h"
#import "LZRegionSelectView.h"
#import "LZVideoListModel.h"
#import "IQKeyboardManager.h"
#import "BlocksKit+UIKit.h"
#import "CitysModel.h"
#import "extobjc.h"
#import "Masonry.h"
#import "LZFightGroupDetailViewController.h"
#import "LZVideoDetailViewController.h"
#import "LZVideoPresenter.h"
#import "CityManager.h"
#import "MJRefresh.h"
#import "LZPlayVideoManager.h"
#import "XBNTimeLimitCountDownCalculator.h"
#import "LZZanAndCollectStatusPresenter.h"
#import "LZFilterViewPresenter.h"
#import "LZCuisineModel.h"
#import "LZHotAreaModel.h"
#import "LZMapLocationManager.h"
#import "LZSearchResultView.h"
#import "LZSearchPresenter.h"
#import "LZVideoListForSearchViewController.h"
#import "LZAlertView.h"
#import "UITableView+LZTableView.h"
#import "LAMerchantDetailViewController.h"
#import "LZLeadingViewPresenter.h"
#import "GVUserDefaults+LZProperties.h"
#import "LZSearchCityViewController.h"
#import "LZNoDataPublicView.h"
#import "AppDelegate.h"

static NSString *kCellIdentifer = @"maincell";

@interface LZHomePageViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,LZ_MainTableViewCellDelegate,UIScrollViewDelegate,LZFilterViewDelegate,LZVideoCellDelegate,LZPlayVideoManagerDelegate>

@property(nonatomic , strong) NSArray *leftItems;
@property(nonatomic , strong) NSArray *rightItems;
@property(nonatomic , strong) UIView * visualView;
@property(nonatomic , strong) UISearchBar *searchBar;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) LZCustomPlayerView *playerView;
@property (nonatomic, strong) LZRestaurantFiltersView *filterView;
@property (nonatomic, strong) LZSearchCollectionView *searchCollectionView;
@property(nonatomic , strong) LZSearchResultView *searchResultView;
@property (nonatomic, strong) LZRegionSelectView *regionSelectView;
@property (weak, nonatomic) IBOutlet UITableView *videoTableView;
@property (nonatomic, strong) NSIndexPath *currentPlayCellIndexPath;
@property (nonatomic, strong) LZVideoCellPresenter *videoCellPresenter;
@property (nonatomic, strong) UIImageView *logoImgView;

@property (nonatomic, strong) NSDictionary *filterKeywordsDic;
@property (nonatomic, assign) int  filterSuccessMark;
@property (nonatomic, assign) int  pageNum;
@property (nonatomic, assign) int  limit;
@property (nonatomic, assign) NSTimeInterval timeStamp;
@property (nonatomic, assign) NSTimeInterval requestTimeStamp;
@property (strong, nonatomic) XBNTimeLimitCountDownCalculator *timeCountDownCalculator;
@property (nonatomic, strong) LZSearchCityViewController *searchCityVC;

@property (nonatomic, assign) BOOL  isFirstShow; //标记是否第一次进入本页, 用于防止多次定位提醒
@property (nonatomic, assign) BOOL  isFirstLoad; //标记是否第一次进入.用于,其他时候返回本页面继续播放视频
/*标记: 筛选时筛选了距离参数, 但当前数据列表的城市和定位城市不一致, 用户点击 同意 切换数据列表城市为当前城市,默认NO*/
@property (nonatomic, assign) BOOL  isChangeCurrentDataCityWhenFilterDicHaveDistance;

@end

@implementation LZHomePageViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.umLogPageViewName = @"首页页面";
    
    [self configureData];
    
    [self configureUI];
    
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    
    BOOL isShowLeadingView = [LZLeadingViewPresenter isShowLeadingView];
    if (!isShowLeadingView) {
        [self startLocationService];
    }
    
    self.isNotShowNavBarShadow = YES;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self releasePlayViewRAM];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    self.isFirstShow = NO;
    
    [LZPlayVideoManager shareManager].playVideoManagerDelegate = self;
    if (self.isFirstLoad == NO) {
        WS(weakSelf);
     self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] goOnPlayWithCellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView tableView:self.videoTableView playCountAddBlock:^(NSInteger totleCount) {
            [weakSelf addViewsCountWithIndexPath:weakSelf.currentPlayCellIndexPath withCount:totleCount];
        }];
    }
    
    
    //=====如果其他页面有对视频进行收藏,点赞操作.这里需要进行对数据源的状态,数据进行更改
    if ([LZZanAndCollectStatusPresenter shareInstance].collectVideoArray.count > 0) {
        BOOL isRefresh = [[LZZanAndCollectStatusPresenter shareInstance] updateTheModelCollectStateWithModleArr:self.dataArr];
        if (isRefresh) {
            [self.videoTableView reloadData];
        }
        [[LZZanAndCollectStatusPresenter shareInstance] resetArray];
    }
    
    if ([LZZanAndCollectStatusPresenter shareInstance].zanArray.count > 0) {
        BOOL isRefresh = [[LZZanAndCollectStatusPresenter shareInstance] updateTheModelZanStateWithModelArr:self.dataArr];
        if (isRefresh) {
            [self.videoTableView reloadData];
        }
        [[LZZanAndCollectStatusPresenter shareInstance] resetArray];
    }
    
    self.isFirstLoad = NO;
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
}

#pragma mark - public method 
- (void)startLocationService {
    // 判断是否切换了语言并弹提示框刷新UI
    if (![[LZLanguageManager shareInstance] showChangeLanguageAlert]) {
        // 如果没有切换语言，则启动定位服务
        [[LZMapLocationManager shareLocationManager] appStartLocationServer];
    }
}

- (void)changeDatasoucreWhenUserLogout
{
    for (int i = 0; i < self.dataArr.count; i ++) {
        LZVideoListModel *m = self.dataArr[i];
        m.isLiked = NO;
        m.isStore = NO;
        m.isCoupons = NO;
        m.isGroupon = NO;
    }
    
    [self.videoTableView reloadData];
}

#pragma mark -
#pragma mark private method
- (void)leftBarButtonAction
{
    self.searchCityVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:self.searchCityVC animated:YES];
}

-(void)showSearchView
{
    self.searchCollectionView.hidden = NO;
    
    self.navigationItem.leftBarButtonItems = nil;
    self.navigationItem.rightBarButtonItems = nil;
    self.navigationItem.titleView = self.searchBar;
    [self.searchBar becomeFirstResponder];
    
    [self.visualView updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(SCREEN_HEIGHT-64);
    }];
    
    [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        [self.view layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        [self.searchBar becomeFirstResponder];
        [self.searchCollectionView refreshUserdefaultData];
        [self requestHotSearch];
    }];
}

-(void)hiddenSearchView{
    self.navigationItem.titleView = self.logoImgView;
    [self navigationItemSetting:_leftItems type:NAVIGATIONITEMSETTING_LEFT];
    [self navigationItemSetting:_rightItems type:NAVIGATIONITEMSETTING_RIGHT];
    
    [self.visualView updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0);
    }];
    
    
    [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        [self.view layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        self.searchBar.text = @"";
    }];
}

/**
 显示搜索结果界面
 
 @param searchContent 搜索内容
 */
-(void)showSearchResultView:(NSString *)searchContent{
    self.searchCollectionView.hidden = YES;
    //如果是一次性的cancel需要热搜和搜索结果一起消失，所以不能设置搜索界面为可现实 ，
    if (self.searchResultView && searchContent.length != 0) {
        self.searchResultView.hidden = NO;
    }
    
    if (searchContent.length == 0) {
        [self hideSearchResultView];
    } else {
        if (!_searchResultView) {
            _searchResultView = [LZSearchResultView new];
            @weakify(self);
            [_searchResultView setSelectBlock:^(NSString *name,NSString *type,NSString *objId) {
                //todo 跳转到视频详情
                DLog(@"idstr %@",name);
                @strongify(self);
                LZVideoListForSearchViewController *vc = [[LZVideoListForSearchViewController alloc] init];
                vc.searchMessage = [name copy];
                vc.searchType = [type copy];
                vc.searchId = [objId copy];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }];
        }
       
        
        BOOL isAdded = NO;
        for (UIView *view in self.visualView.subviews) {
            isAdded = [view isEqual:_searchResultView];
        }
        
        if (!isAdded) {
            [self.visualView addSubview:_searchResultView];
            
            [_searchResultView makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
            }];
        }
        
        [self requestKeywordsSearch:searchContent];
    }
}


/**
 隐藏搜索结果界面
 */
-(void)hideSearchResultView{
    self.searchCollectionView.hidden = NO;
    
    [_searchResultView removeFromSuperview];
    _searchResultView = nil;
    
    self.searchBar.text = @"";
}



/**
 离开页面,释放播放器内存
 */
- (void)releasePlayViewRAM
{
    [[LZPlayVideoManager shareManager] stopPlayWithPlayerView:self.playerView];
}


/**
 添加浏览次数

 @param indexP <#indexP description#>
 @param totleCount <#totleCount description#>
 */
- (void)addViewsCountWithIndexPath:(NSIndexPath *)indexP withCount:(NSInteger)totleCount
{
    LZVideoListModel *m = self.dataArr[self.currentPlayCellIndexPath.row];
    m.playCount = totleCount;
    LZVideoTableViewCell *cell = [self.videoTableView cellForRowAtIndexPath:indexP];
    [cell getViewsCountLabel].text = [NSString stringWithFormat:@"%ld",(long)totleCount];
}

#pragma mark -
#pragma mark network method

/**
 下拉获取最新列表
 */
- (void)downLoadNewVideoListData
{
    self.currentPlayCellIndexPath = nil;//下拉刷新,重新播放
    self.limit = 10;
    [self getVideoListActionWithPage:1 TimeStamp:0 andIsDown:YES];
}


/**
 上拉加载
 */
- (void)upLoadMoreVideoListData
{
    [self getVideoListActionWithPage:self.pageNum TimeStamp:self.requestTimeStamp andIsDown:NO];
}

- (void)getVideoListActionWithPage:(int)page TimeStamp:(NSTimeInterval )timeStamp andIsDown:(BOOL)isDown
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    if (_filterKeywordsDic.count != 0) {
        dic = [[NSMutableDictionary alloc] initWithDictionary:_filterKeywordsDic];
    }
    if ([LZMapLocationManager shareLocationManager].currentLocation != nil) {
        double lat = [LZMapLocationManager shareLocationManager].currentLocation.coordinate.latitude;
        double lon = [LZMapLocationManager shareLocationManager].currentLocation.coordinate.longitude;
        dic[@"mapLocationLatitude"] = [NSNumber numberWithDouble:lat];
        dic[@"mapLocationLongitude"] = [NSNumber numberWithDouble:lon];
    }
    
    if ([CityManager shareManager].currentShowCityModel) {
        dic[@"cityCode"] = [CityManager shareManager].currentShowCityModel.cityNO;
    }

    @weakify(self);
   [LZVideoPresenter getVideoListWithParameter:[dic copy] PageNum:page PageLimit:self.limit TimeStamp:timeStamp ResultSuccess:^(NSArray *listArr, int totlePage, int totleCount, int currentPage, NSTimeInterval timeStamp) {
       @strongify(self);
       if (isDown) {
           self.timeStamp = timeStamp/1000;
           self.requestTimeStamp = timeStamp;
           [self.videoTableView.mj_header endRefreshing];
           if (self.videoTableView.mj_footer.state == MJRefreshStateNoMoreData) {
               self.videoTableView.mj_footer.state = MJRefreshStateIdle;
           }
           if (self.dataArr.count > 0) {
               [self.dataArr removeAllObjects];
           }
           self.pageNum =  currentPage + 1;
           [self.dataArr addObjectsFromArray:listArr];
           
           if (totlePage == 0) {
               [self.videoTableView setNullStringFooterText];
               [self.videoTableView.mj_footer endRefreshingWithNoMoreData];
           }
           
       }else{
           [self.videoTableView.mj_footer endRefreshing];
           
           if (self.pageNum == currentPage) {
               if (currentPage >= totlePage) {
                   [self.videoTableView setNoMoreDataFooterText];
                   [self.videoTableView.mj_footer endRefreshingWithNoMoreData];
               }
               [self.dataArr addObjectsFromArray:listArr];
               self.pageNum ++;
           }
           
        }
       if (self.dataArr.count == 0) {
           [self.timeCountDownCalculator timeLimitCountDownClear];
           self.timeCountDownCalculator = nil;
           [self releasePlayViewRAM];
           [LZNoDataPublicView showNoDataViewInView:self.videoTableView];
       }else{
           [LZNoDataPublicView hiddenNoDataViewInView:self.videoTableView];
       }
       [self.videoTableView fd_reloadDataWithoutInvalidateIndexPathHeightCache];
       if (isDown && self.dataArr.count>0 && (self.isViewLoaded && self.view.window)) {
           //默认播放第一个视频
           self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self.videoTableView cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
               [self addViewsCountWithIndexPath:self.currentPlayCellIndexPath withCount:totleCount];
           }];
       }
       
   } ResultFailed:^(NSString *remind) {
       @strongify(self);
       if (self.dataArr.count == 0) {
           [self.timeCountDownCalculator timeLimitCountDownClear];
           self.timeCountDownCalculator = nil;
       }
       [self.videoTableView.mj_header endRefreshing];
       [self.videoTableView.mj_footer endRefreshing];
   }];
}

- (void)getFilterKeyWordsAction
{
    @weakify(self);
    [LZFilterViewPresenter getFilterKeyWordsWithType:@"1" ResultSuccess:^(NSArray *listDataArr) {
        @strongify(self);
        self.cuisineArr = listDataArr;
        self.filterSuccessMark += 1;
        [self configureFilterView];
        
    } ResultFailed:^(NSString *remind) {
        
    }];
    
    [LZFilterViewPresenter getFilterKeyWordsWithType:@"0" ResultSuccess:^(NSArray *listDataArr) {
        @strongify(self);
        self.hotAreaArr = listDataArr;
        self.filterSuccessMark += 1;
        [self configureFilterView];
        
    } ResultFailed:^(NSString *remind) {
        
    }];
}


/**
 热搜请求
 */
- (void)requestHotSearch {
    LZSearchPresenter *searchPresenter = [LZSearchPresenter new];
    [searchPresenter hotSearch:@"1" onSuccess:^(id data) {
        //todo 请求后发送给 searchCollectionView 去显示数据
        [self.searchCollectionView refreshData:data[@"data"]];
        
    } onFail:^(NSString *fail) {
        DLog(@"fail %@",fail);
    }];
}


/**
 关键字搜索
 
 @param searchContent 搜索关键字
 */
-(void)requestKeywordsSearch:(NSString *)searchContent{
    LZSearchPresenter *searchPresenter = [LZSearchPresenter new];
    @weakify(self);
    [searchPresenter keywordsSearch:searchContent type:1 onSuccess:^(id data) {
        @strongify(self);
        [self.searchResultView refreshDatas:data];
    } onFail:^(NSString *fail) {
        DLog(@"fail %@",fail);
    }];
}


#pragma mark -
#pragma mark currentTimer 倒计时相关
- (void)setTimeStamp:(NSTimeInterval)timeStamp
{
    _timeStamp = timeStamp;
    // 开起计时器
    [self startTimeCountDown];
}

- (void)startTimeCountDown {
    if (self.timeCountDownCalculator) {
        return;
    }
    // ******************** 创建计时器 ********************
    self.timeCountDownCalculator = [XBNTimeLimitCountDownCalculator new];
    
    // 取出服务器时间
    self.timeCountDownCalculator.remainTimeInterval = self.timeStamp;
    
    // 以服务器时间为标准时间开始计算
    WS(weakSelf);
    [self.timeCountDownCalculator addProcessBlock:^(NSTimeInterval remain) {
        weakSelf.timeStamp += 1;
    } cancelBlock:^{
        DLog(@"结束了");
    }];
    
    [self.timeCountDownCalculator timeLimitCountDownResume];
    
}

#pragma mark -
#pragma mark configure UI
- (void)configureUI
{
    self.videoTableView.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
    _filterSuccessMark = 0;
    [self registerCell];
    [self configFooterViewUI];
    [self getFilterKeyWordsAction];
    [self configureRefresh];
    [self configNavigationBar];
    [self configureVideoSearchView];
}

- (void)configFooterViewUI {
    self.videoTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
}

- (void)configureRefresh
{
    self.videoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downLoadNewVideoListData)];
    [self.videoTableView configHeaderRefreshText];
    
    self.videoTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMoreVideoListData)];
    [self.videoTableView configFooterRefreshText];
}

- (void)configureFilterView
{
    if (_filterSuccessMark < 2) {
        return;
    }
    UIWindow *w = [UIApplication sharedApplication].keyWindow;
    
    self.filterView = [[LZRestaurantFiltersView alloc] init];
    NSMutableArray *cuisineArrTemp = [[NSMutableArray alloc] init];
    for (LZCuisineModel *m in self.cuisineArr) {
        LZCuisineModel *mTemp = [[LZCuisineModel alloc] init];
        mTemp.cuisineID = m.cuisineID;
        mTemp.name = m.name;
        mTemp.selected = m.selected;
        [cuisineArrTemp addObject:mTemp];
    }
    
    NSMutableArray *hotAreaArrTemp = [[NSMutableArray alloc] init];
    for (LZHotAreaModel *m in self.hotAreaArr) {
        LZHotAreaModel *mTemp = [[LZHotAreaModel alloc] init];
        mTemp.hotAreaID = m.hotAreaID;
        mTemp.name = m.name;
        mTemp.selected = m.selected;
        [hotAreaArrTemp addObject:mTemp];
    }
    self.filterView.isForRestaurant = NO;
    self.filterView.cuisineDataArr = cuisineArrTemp;
    self.filterView.hotAreasDataArr = hotAreaArrTemp;
    self.filterView.filterViewDelegate = self;
    [w addSubview:self.filterView];
    [self.filterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
}

- (void)configureVideoSearchView
{
    [_visualView addSubview:self.searchCollectionView];
    
    [self.searchCollectionView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.leading.and.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(-49).priority(750);
        
    }];
}

- (void)registerCell
{
    [self.videoTableView registerClass:[LZVideoTableViewCell class] forCellReuseIdentifier:kCellIdentifer];
}

-(void)configNavigationBar{
    
    ///背景模糊    
    _visualView = [[UIView alloc] init];
    _visualView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_visualView];
    
    [_visualView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.top).offset(0);
        make.leading.mas_equalTo(0);
        make.width.equalTo(CGRectGetWidth(self.view.frame));
        make.height.mas_equalTo(0);
    }];
    
    _searchBar = [UISearchBar new];
    _searchBar.showsCancelButton = YES;
    _searchBar.placeholder = LZLocalizedString(@"search_placeholder_search", nil);
    _searchBar.delegate = self;
    _searchBar.tintColor = UIColorFromRGB(0xff6600, 1);
    
    UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
    if (searchField) {
        [searchField setBackgroundColor:[UIColor whiteColor]];
        searchField.layer.cornerRadius = 14.0f;
        searchField.layer.borderColor = UIColorFromRGB(0xcccccc, 1).CGColor;
        searchField.layer.borderWidth = 1;
        searchField.layer.masksToBounds = YES;
        
    }
    
    UIButton *searchButton = ({
        UIImage *btn_image = [UIImage imageNamed:@"search_icon"];

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 40, 40);
        [button setImage:btn_image forState:UIControlStateNormal];
        [button setNormalImageEdgeInsets:UIEdgeInsetsMake(0, CGRectGetWidth(button.bounds)-btn_image.size.width, 0, 0)];

        @weakify(self)
        [button bk_addEventHandler:^(UIButton *sender) {
            @strongify(self)
            
            [self showSearchView];
            
        } forControlEvents:UIControlEventTouchUpInside];
        button;
    });
    
    UIButton *filterButton = ({
        UIImage *btn_image = [UIImage imageNamed:@"filtrate_icon"];

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, btn_image.size.width+9, 40);
        [button setImage:btn_image forState:UIControlStateNormal];
        [button setNormalImageEdgeInsets:UIEdgeInsetsMake(0, CGRectGetWidth(button.bounds)-btn_image.size.width, 0, 0)];

        @weakify(self)
        [button bk_addEventHandler:^(id sender) {
            @strongify(self)
            [self.filterView showSelfAnimation];
        } forControlEvents:UIControlEventTouchUpInside];
        button;
    });
    
    _leftItems = @[self.regionSelectView];
    
    _rightItems = @[filterButton,searchButton];
    
    [self navigationItemSetting:_leftItems type:NAVIGATIONITEMSETTING_LEFT];
    
    [self navigationItemSetting:_rightItems type:NAVIGATIONITEMSETTING_RIGHT];
    
}

-(void)configureData
{
    _dataArr = @[].mutableCopy;
    self.isFirstShow = YES;
    self.isFirstLoad = YES;
    self.isChangeCurrentDataCityWhenFilterDicHaveDistance = NO;
    [[CityManager shareManager] addObserver:self forKeyPath:@"currentShowCityModel" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}

#pragma mark -
#pragma mark filterview delgate
- (void)returnTheFileterResult:(NSDictionary *)dic
{
    //如果筛选项中包含了距离参数. 并且当前定位的城市和城市列表选择的城市不一致.提醒用户是否要切换城市
    if ([dic.allKeys containsObject:@"distance"] && ![[CityManager shareManager].locationCityModel.cityNO isEqualToString:[CityManager shareManager].currentShowCityModel.cityNO]) {
        
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"filter_distance_not_same_city", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
            [alert show];
            @weakify(self);
            alert.clickButtonIndexBlock = ^(NSInteger index) {
                @strongify(self);
                if (index == 1) {//数据列表切换到当前定位城市
                    //数据切换到当前
                    self.isChangeCurrentDataCityWhenFilterDicHaveDistance = YES;
                    self.filterKeywordsDic = dic;
                    self.pageNum = 1;
                    self.timeStamp = 0;
                    self.requestTimeStamp = 0;
                    self.currentPlayCellIndexPath = nil;
                    [CityManager shareManager].currentShowCityModel = [CityManager shareManager].locationCityModel;
                    [self.videoTableView.mj_header beginRefreshing];
                }else{
                    self.filterKeywordsDic = dic;
                    self.pageNum = 1;
                    self.timeStamp = 0;
                    self.requestTimeStamp = 0;
                    self.currentPlayCellIndexPath = nil;
                    [self.videoTableView.mj_header beginRefreshing];
   
                }
            };
     }else{//如果没有包含,则直接筛选
        _filterKeywordsDic = dic;
        _pageNum = 1;
        _timeStamp = 0;
        self.requestTimeStamp = 0;
        self.currentPlayCellIndexPath = nil;
        [self.videoTableView.mj_header beginRefreshing];
    }

}

#pragma mark -
#pragma mark search city KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"currentShowCityModel"]) {

        [self.regionSelectView changeTitle:[CityManager shareManager].currentShowCityModel.name];
        
        self.searchCityVC.selectCityModel = [CityManager shareManager].currentShowCityModel;
        
        [self hiddenSearchView];
        
        if (self.isChangeCurrentDataCityWhenFilterDicHaveDistance == NO) {//如果不是筛选距离引起的进入此方法.则应是手动切换城市进入.则需要清楚之前的筛选参数
            if (_filterKeywordsDic.count > 0) {
                _filterKeywordsDic = nil;
            }
            
            [self.filterView clearFilterResult];
        }
        
        self.currentPlayCellIndexPath = nil;
        
        [self.videoTableView.mj_header beginRefreshing];

        if ((self.isViewLoaded && self.view.window && self.isChangeCurrentDataCityWhenFilterDicHaveDistance == NO) || self.isFirstShow) {
            DLog(@"是当前显示vc")
            // 如果定位的城市不在app服务的城市内 / 00001是定位时不在城市列表默认的cityno
            if ([[CityManager shareManager].currentShowCityModel.cityNO isEqualToString:@"00001"]) {
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"iphone_location_not_server_city_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                [alert show];
                
                alert.clickButtonIndexBlock = ^(NSInteger index) {
                    if (index == 1) {
                        // 去选择城市
                        [self leftBarButtonAction];
                    }
                };
            }
        }
        
        if (self.isChangeCurrentDataCityWhenFilterDicHaveDistance == YES) {//复原初始值
            self.isChangeCurrentDataCityWhenFilterDicHaveDistance = NO;
        }
    }
}
#pragma mark -
#pragma mark UISearchBarDelegate
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self hideSearchResultView];
    [self hiddenSearchView];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
        //todo 显示搜索结果界面，隐藏热搜界面
        [self showSearchResultView:searchText];
}

/* **********  以下是用于解决 UISearchBar失去第一响应者身份后,取消按钮不执行点击事件 的问题 ********** */

//UISearchBar结束编辑

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    
    [self searchBarResignAndChangeUI];
    
}

// searchBarResignAndChangeUI方法的实现如下：

- (void)searchBarResignAndChangeUI{
    
    [_searchBar resignFirstResponder];//失去第一响应
    
    [self changeSearchBarCancelBtnTitleColor:_searchBar];//改变布局
    
}

- (void)changeSearchBarCancelBtnTitleColor:(UIView *)view{
    
    if (view) {
        
        if ([view isKindOfClass:[UIButton class]]) {
            
            UIButton *getBtn = (UIButton *)view;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [getBtn setEnabled:YES];//设置可用
                
                [getBtn setUserInteractionEnabled:YES];
            });
            
            [getBtn setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateReserved];
            
            [getBtn setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateDisabled];
            
            return;
            
        }else{
            
            for (UIView *subView in view.subviews) {
                [self changeSearchBarCancelBtnTitleColor:subView];
            }
            
        }
    }else{
        return;
    }
}

/* ************************************************************************ */

#pragma mark -
#pragma mark tableview delegate datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZVideoListModel *m = self.dataArr[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier:kCellIdentifer cacheByKey:m.videoId configuration:^(id cell) {
        LZVideoTableViewCell *cellTemp = (LZVideoTableViewCell *)cell;
        [cell loadDataWithIndex:indexPath WithShowHeadView:YES showCellBtns:YES showCouponAndGroupsView:YES];
        cellTemp.model = m;
        
    }];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifer];
    LZVideoListModel *m = self.dataArr[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.mainDelegate = self;
    cell.cellClickDelegate = self;
    [cell loadDataWithIndex:indexPath WithShowHeadView:YES showCellBtns:YES showCouponAndGroupsView:YES];
    m.currentTime = self.timeStamp;
    cell.model = m;
    [cell startTimeDown];
    
    return cell;
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if(!decelerate){//缓慢拖动.手指离开时
        WS(wSelf);
        self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self.videoTableView cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
           [wSelf addViewsCountWithIndexPath:wSelf.currentPlayCellIndexPath withCount:totleCount];
        }];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
   WS(wSelf);
   self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenTableViewStopScrollWithTableView:self.videoTableView cellIndexPath:self.currentPlayCellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
       [wSelf addViewsCountWithIndexPath:wSelf.currentPlayCellIndexPath withCount:totleCount];
   }];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //滑动时判断当前播放的cell是否已经离开屏幕.已经离开,停止播放
    [[LZPlayVideoManager shareManager] removePlayViewWhenTableViewDidScrollWithTableView:self.videoTableView cellIndexPath:self.currentPlayCellIndexPath];
}

#pragma mark -
#pragma mark cell  delegate
/**
 cell 按钮协议方法
 index: 0点赞 1收藏  2信息  3分享   4视频详情  5抢券详情   6拼团详情  9餐厅详情
 */

- (void)clickCellButtonWithIndex:(VideoCellDelegateClickEventCode)index andCellIndexPath:(NSIndexPath *)cellIndexPath andModel:(id)model andOtherObject:(id)object refreshBlock:(void (^)(VideoCellRefreshType, BOOL))refreshBlock {
    
    if (index == kVideoCellDelegate_restaurantDetailEvent) {
        LZVideoListModel *m = (LZVideoListModel *)model;
        LAMerchantDetailViewController *vc = [[LAMerchantDetailViewController alloc] init];
        vc.restaurantId = [m.sellerId copy];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];

    }else{
       [self.videoCellPresenter dealClickCellButtonIndex:index andCellIndexPath:cellIndexPath andNavigationController:self.navigationController andHidesBottomBarWhenPushed:YES andCellModel:model andOtherObject:object andRefreshBlcok:refreshBlock];
    }
}

/**
 点击视频海报播放协议
 */
- (void)playVideoWhenClickVideoCoverImgWithIndex:(NSIndexPath *)cellIndexPath
{
    [self.videoTableView scrollToRowAtIndexPath:cellIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    WS(wSelf);
    self.currentPlayCellIndexPath = [[LZPlayVideoManager shareManager] playVideoWhenClickVideoCoverImgWithIndexPath:cellIndexPath playerView:self.playerView playCountAddBlock:^(NSInteger totleCount) {
        [wSelf addViewsCountWithIndexPath:wSelf.currentPlayCellIndexPath withCount:totleCount];
    }];
    
}

#pragma mark -
#pragma mark  播放控制器获取资源delegate
- (NSString *)playVideoManagerGetVideoUrlWith:(NSIndexPath *)cellIndexPath
{
    LZVideoListModel *m = self.dataArr[cellIndexPath.row];
    
    return m.videoUrl;
}

- (UIView *)playVidewManagerGetPlayBackgroundViewWith:(NSIndexPath *)cellIndexPath
{
    LZVideoTableViewCell *cell = [self.videoTableView cellForRowAtIndexPath:cellIndexPath];
    
    return cell.playerBgView;
}

- (NSString *)playVideoManagerGetVideoIdWithIndexPath:(NSIndexPath *)cellIndexPath
{
   LZVideoListModel *m = self.dataArr[cellIndexPath.row];
    
    return m.videoId;
}

#pragma mark -
#pragma mark 控件初始化
- (LZVideoCellPresenter*)videoCellPresenter {
    if (_videoCellPresenter) {
        return _videoCellPresenter;
    }
    
    _videoCellPresenter = [[LZVideoCellPresenter alloc] init];
    return _videoCellPresenter;
}

- (LZCustomPlayerView *)playerView
{
    if (!_playerView) {
        _playerView = [[LZCustomPlayerView alloc] init];
        _playerView.playCircle = YES;
    }
    
    return _playerView;
}

- (LZSearchCollectionView *)searchCollectionView
{
    if (!_searchCollectionView) {
        _searchCollectionView = [[LZSearchCollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:[UICollectionViewFlowLayout new]];
        @weakify(self)
        [_searchCollectionView setMostSearchSelectBlock:^(NSString *searchContent) {
            @strongify(self)
            self.searchBar.text = searchContent;
            [self showSearchResultView:searchContent];
        }];
        
        [_searchCollectionView setHistorySelectBlock:^(NSString *idStr,NSString *type,NSString *objId) {
            //todo 跳转视频详情
            DLog(@"id %@",idStr);
            @strongify(self);
            LZVideoListForSearchViewController *vc = [[LZVideoListForSearchViewController alloc] init];
            vc.searchMessage = [idStr copy];
            vc.searchType = [type copy];
            vc.searchId = [objId copy];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }];
    }
    
    return _searchCollectionView;
}

- (LZRegionSelectView *)regionSelectView
{
    if (!_regionSelectView) {
        _regionSelectView = [[LZRegionSelectView alloc]initWithFrame:CGRectMake(0, 0, 63, 40)];
        _regionSelectView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftBarButtonAction)];
        [_regionSelectView addGestureRecognizer:tap];
    }
    return _regionSelectView;
}

- (UIImageView *)logoImgView
{
    if (!_logoImgView) {
        _logoImgView = [[UIImageView alloc] init];
        _logoImgView.frame = CGRectMake(0, 0, 61, 15.5);
        _logoImgView.image = [UIImage imageNamed:@"logo_new"];
    }
    
    return _logoImgView;
}

- (LZSearchCityViewController *)searchCityVC
{
    if (!_searchCityVC) {
        _searchCityVC = [[LZSearchCityViewController alloc] init];
    }
    
    return _searchCityVC;
}
@end
